let express = require("express");
let websocket = require("ws");

let app = express();
// 创建一个 websocket的服务对象
let wss = new websocket.Server({ port: 3001 });

wss.on("connection", (ws) => {
  console.log(ws);
  console.log("socket已经启动");
  ws.on("message", (message) => {
    // 客户端返回的消息
    // 广播消息
    wss.clients.forEach(function each(client) {
      if (client.readyState === Websocket.OPEN) {
        client.send(data, { binary: isBinary });
      }
    });
    console.log("received:%s", message);
    // 服务器主动发送消息
    // 服务器接受到消息后，返回这个消息内容
    ws.send(message.toString());
  });
});
app.listen(3000, () => {
  console.log("Server run on http://127.0.0.1:3000");
});
